package com.woniu.util;

import io.jsonwebtoken.*;
import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@ToString
@Data
@ConfigurationProperties(prefix = "jwt")
public class JwtUtil {
    private String alg;
    private String typ;
    private Long expire;
    private String id;
    private String subject;
    private String salt;

    public String createToken(String userName) {
        // 创建JwtBuilder
        JwtBuilder builder = Jwts.builder();
        // 设置头部
        builder.setHeaderParam("alg", alg);
        builder.setHeaderParam("typ", typ);
        // 设置载荷
        long time = 600 * 1000 * expire;
        builder.setId(id);
        builder.setSubject(subject);
        builder.setExpiration(new Date(System.currentTimeMillis() + time));
        // 设置自定义内容 <key , value>
        builder.claim("userName", userName);
        // 设置验证签名
        builder.signWith(SignatureAlgorithm.HS256, salt);
        // 组合生成token
        String token = builder.compact();
        return token;
    }

    public String parseToken(String token) {
        try {
            // 得到token解析器
            JwtParser parser = Jwts.parser();
            // 再设置盐
            Jws<Claims> claimsJws = parser.setSigningKey(salt).parseClaimsJws(token);
            // 2: 得到载荷信息：
            Claims body = claimsJws.getBody();
            return (String) body.get("userName");
        } catch (ExpiredJwtException e) {
            throw new ExpiredJwtException(null, null, "token已过期", e);
        } catch (SignatureException e) {
            throw new SignatureException("token不正确", e);
        } catch (RuntimeException e) {
            throw new RuntimeException("token解析异常", e);
        }
    }
}
